package service;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.FansDao;
import dao.UserDao;
import entry.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute("user");
        String userId = req.getParameter("authorId");
        String logout = req.getParameter("logout");
        UserDao userDao = new UserDao();
        FansDao fansDao = new FansDao();

        if (logout != null && logout.equals("yes")){
            // 注销用户
            userDao.deleteUser(user.getUserId());
            // 粉丝信息删除
            fansDao.deleteFansIfLogout(user.getUserId());
            String path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/image";
            User.deletePhoto(user.getUsername(), path);
            resp.getWriter().write("success");
            return;
        }

        if (userId == null){
            // 是要获取用户信息
            resp.setContentType("application/json; charset=utf8");
            // 查询出用户的粉丝信息
            List<User> fansById = fansDao.getFansById(user.getUserId());
            user.setFans(fansById);
            String retString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(retString);
            return;
        }

        // 是要核查是否为当前用户
        resp.setContentType("text/html; charset=utf8");
        int id = Integer.parseInt(userId);
        if (id == user.getUserId()){
            resp.getWriter().write("same");
        }else {
            resp.getWriter().write("different");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String exit = req.getParameter("exit");
        HttpSession session = req.getSession(false);
        if (exit != null && exit.equals("yes")){
            // 要退出登录
            session.removeAttribute("user");
            resp.getWriter().write("success");
        }

        // 验证是否登录了
        if (session == null){
            resp.getWriter().write("null");
            return;
        }
        User user = (User)session.getAttribute("user");
        if (user == null){
            resp.getWriter().write("null");
        }
    }
}
